﻿/* InternetHelper
 */

//待完善：单元测试
namespace LSLib.Net
{
    using System;
    using System.Net.NetworkInformation;
    using System.Text;

    public class InternetHelper
    {
        #region 检查网络是否可以连接互联网
        /// <summary>用于检查网络是否可以连接互联网
        /// </summary>
        /// <returns>true:连接成功,false:连接失败</returns>
        public static bool IsConnectInternet()
        {
            int lpdwFlags;
            return API.Net.InternetGetConnectedState(out lpdwFlags, 0);
        }

        /// <summary>用于检查IP地址或域名是否可以使用TCP/IP协议访问(使用Ping命令)
        /// </summary>
        /// <param name="IpOrDomainName">输入参数,表示IP地址或域名</param>
        /// <returns>true:Ping成功,false:Ping失败</returns>
        public static bool PingIpOrDomainName(string IpOrDomainName)
        {
            try
            {
                Ping objPingSender = new Ping();

                int intTimeOut = 120;
                byte[] buffer = Encoding.UTF8.GetBytes(string.Empty);

                PingOptions objPingOptions = new PingOptions();
                objPingOptions.DontFragment = true;

                PingReply objPingReply = objPingSender.Send(IpOrDomainName, intTimeOut, buffer, objPingOptions);
                return (objPingReply.Status == IPStatus.Success);
            }
            catch (Exception) { return false; }
        }
        #endregion

    }
}
